package com.example.wendao.view.ui.fragment;


import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.wendao.App;
import com.example.wendao.R;
import com.example.wendao.common.PageUtils;
import com.example.wendao.model.entity.User;
import com.example.wendao.view.adapter.FansListAdapter;
import com.example.wendao.viewmodel.UserViewModel;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class InfoFansFragment extends Fragment {

    private FansListAdapter adapter = new FansListAdapter();
    private UserViewModel userViewModel = null;
    private RecyclerView recyclerView;
    private User user;
    private SwipeRefreshLayout srl;
    public InfoFansFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_information_fans, container, false);
        recyclerView = view.findViewById(R.id.fans_recycler);
        srl = view.findViewById(R.id.srl_news_list);
        binds();
        userViewModel = new ViewModelProvider(App.getInstance()).get(UserViewModel.class);
        userViewModel = new ViewModelProvider(App.getInstance()).get(UserViewModel.class);
        user = userViewModel.getCurrentUser();
        userViewModel.getAllFans().observe(this.getViewLifecycleOwner(), adapter::submitList);
        PageUtils.initRecyclerView(recyclerView, adapter, new LinearLayoutManager(this.getActivity()));
        return view;
    }


    private void binds() {
        // 模拟下拉刷新
        srl.setOnRefreshListener(() -> {
            srl.setRefreshing(true);
            Observable.just(0)
                    .delay(1, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnNext(i -> {
                        srl.setRefreshing(false);
                        adapter.submitList(null);
                        userViewModel.getAllFans().observe(getActivity(), users -> adapter.submitList(users));
                    }).subscribe();
        });
    }

}